<!-- 大转盘 -->
<template>
	<view class="index">
		<!-- 导航栏开始 -->
		<view class="">
			<view class="navbar" :style="{paddingTop: `${statusBarHeight + 7}`  + 'px'}">
				<view class="left" @tap="back">
					<u-icon name="arrow-left" color="#FFF" size="34"></u-icon>
					<view class="">返回</view>
				</view>

				<view class="right" :style="{left: `${screenWidth / 2 - 45 }`+ 'px'}">
					幸运大转盘
				</view>
			</view>
			<!-- 导航栏结束 -->

			<!-- 标题开始 -->
			<view class="title">
				<image src="https://mystore-1304299581.cos.ap-guangzhou.myqcloud.com/static/image/turntable_title.png"
					mode=""></image>
			</view>
			<!-- 标题结束 -->

			<!-- 降落伞开始 -->
			<view class="balloon_s">
				<image :src="balloon_s" mode=""></image>
			</view>
			<view class="balloon">
				<image :src="balloon" mode=""></image>
			</view>
			<!-- 降落伞结束 -->

			<view class="almost-lottery__head tc">
				<view :class="['action', isApple && 'action-shadow']">
					<text class="gold"></text>
					<text class="content">我的积分：<text class="num">{{goldCoin || 0}}</text></text>
				</view>
			</view>
			<!-- 转盘 -->
			<view class="almost-lottery__wheel">
				<almost-lottery :canvasWidth="canvasData.width" :canvasHeight="canvasData.height" :strFontSize="14"
					:strMarginOutside="10" :ringCount="2" :duration="1" :prizeList="prizeList" :prizeIndex="prizeIndex"
					@reset-index="prizeIndex = -1" @draw-start="handleDrawStart" @draw-end="handleDrawEnd"
					@finish="handleDrawFinish" v-if="prizeList.length" />
			</view>

			<!-- 活动规则 -->
			<view class="rule x-f pa" v-if="false">
				<text class="">活动规则</text>
				<u-icon name="arrow-right" color="#FFF" size="20"></u-icon>
			</view>
			<view class="pr" v-if="show">
				<!-- 阴影 -->
				<view class="showdow pa">
					<image :src="showdow" mode=""></image>
				</view>
				<view class="recommend_content">
					<view class="xxx x-c" style="padding: 20rpx;color: #fff;">
						每次游戏将花费您{{userdScore.consume_points}}积分
						<view class="" v-if="free_count != 0">，可免费{{free_count || 0}}次数</view>
					</view>
					<view class="recommend">
						<text>更多推荐</text>
					</view>

					<view class="recommend_box x-ac pa">
						<view class="text">
							<view class="text_A">做任务赚积分</view>
							<view class="text_B">快去看看你有多少积分可赚</view>

							<view class="text_C" @click="jumpTask">
								<text>立即前往</text>
								<u-icon name="arrow-right" color="#FFF" size="18"></u-icon>
							</view>
						</view>

						<view class="gift_img">
							<image :src="gift_img" mode=""></image>
						</view>
					</view>
				</view>
			</view>

		</view>
		<regret :show="show_regret" @close="close_regret"></regret>
		<congratulations :show="show_congratulations" @close="close_regret" :prise="targetName"></congratulations>
		<view class="finish_box pf" v-if="finish_status">
			<view class="card pa">
				<view class="name x-c">温馨提示</view>
				<view class="text x-c">每次游戏将花费您{{userdScore.consume_points}}积分</view>
				<view class="btn x-ac">
					<view class="cancel" @click="cancel">取消</view>
					<view class="finally" @click="finall">确定</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		mapState
	} from 'vuex';
	import regret from './regret.vue'
	import congratulations from './congratulations.vue'
	export default {
		components: {
			regret,
			congratulations
		},
		data() {
			return {
				finish_status: true,
				balloon_s: this.imgUrl + 'balloon_s.png',
				balloon: this.imgUrl + 'balloon.png',
				back_img: this.imgUrl + 'back.png',
				showdow: this.imgUrl + '	showdow_g.png',
				gift_img: this.imgUrl + 'gift_g.png',
				show: false, // 转盘未绘制完成时下部分不显示
				show_regret: false, // 未中奖弹窗显示
				show_congratulations: false, // 中奖弹窗显示
				//画布大小
				canvasData: {
					width: 280,
					height: 280
				},
				// 是否正在抽奖中，避免重复触发
				prizeing: false,
				// 中奖下标
				prizeIndex: -1,
				// 中奖类目名称
				targetName: '',
				// 奖品是否设有库存
				onStock: true,
				// 是否由前端控制概率，默认不开启
				onFrontend: false,
				// 权重随机数的最大值
				weightTotal: 0,
				// 权重数组
				weightArr: [],
				// 奖品数据
				prizeList: [],
				// 每次消耗的金币数
				goldNum: 20,
				free_count: 0, // 免费次数
			}
		},
		computed: {
			...mapState({
				prizeName: state => state.game.prizeName,
				priseRes: state => state.game.priseRes,
				a: state => state.game.aa,
				user: state => state.user.user,
				statusBarHeight: state => state.init.systemInfo.statusBarHeight, // 状态栏高度;
				screenWidth: state => state.init.systemInfo.screenWidth, // 屏幕宽度
				goldCoin: state => state.init.points, // 剩余积分
				key: state => state.game.key, // 游戏key值
				userdScore: state => state.game.priseRes // 花费积分// 游戏key值
			})
		},
		onLoad() {
			// 请求奖品数据
			this.getPrizeList()
		},
		mounted() {
			this.free_count = this.userdScore.free_count
		},
		onUnload() {
			uni.hideLoading()
		},
		methods: {
			cancel() {
				this.$Router.back(1)
			},
			finall() {
				this.finish_status = false
			},
			jumpTask() {
				this.$Router.replace({
					path: '/pages/user/score/task/index'
				})
			},
			back() {
				this.$Router.back(1)
			},
			//关闭未中奖弹窗
			close_regret() {
				this.show_regret = false
				this.show_congratulations = false
			},

			// 重新生成
			handleInitCanvas() {
				clearCacheFile()

				this.prizeList = []
				this.getPrizeList()

			},
			// 获取奖品列表
			getPrizeList() {
				setTimeout(()=>{
					let data = this.priseRes.gamePrize
					if (data.length) {
						// stock 奖品库存
						// weight 中奖概率，数值越大中奖概率越高
						this.prizeList = data
						//转盘下半部分的也显示出来
						this.show = true
					}
				},300)
			},
			// 本次抽奖开始
			handleDrawStart() {
				if (this.prizeing) return
				this.prizeing = true
				// 抽奖接口
				let obj = {
					key: this.key,
				}
				// 调用抽奖接口成功之后重新获取用户剩余积分
				this.$store.dispatch('game/get_prise', obj).then(res => {
					if (res.status === 1) {
						this.$store.dispatch('init/get_Points');
						if (this.free_count > 0) {
							this.free_count--
						}
						// 还有免费数次或者剩余金币足够抽一次
						if (this.goldCoin >= this.goldNum) {
							this.tryLotteryDraw();
						} else {
							this.prizeing = false
						}
					}
				})

			},
			// 尝试发起抽奖
			tryLotteryDraw() {
				this.$store.dispatch('game/get_gameDetail','dzp').then(res=> {
					this.userdScore.free_count = res.data.free_count 
				})
				// 判断是否由前端控制概率
				if (this.onFrontend) {
					this.localGetPrizeIndex()
				} else {
					this.remoteGetPrizeIndex()
				}
			},
			// 本地获取中奖下标
			localGetPrizeIndex() {
				console.warn('###当前处于前端控制中奖概率，安全起见，强烈建议由后端控制###')
				// 前端控制概率的情况下，需要拿到最接近随机权重且大于随机权重的值
				// 后端控制概率的情况下，通常会直接返回 prizeId
				if (!this.weightTotal) {
					console.warn('###当前已开启前端控制中奖概率，但是奖品数据列表中的 weight 参数似乎配置不正确###')
					return
				}

				// 注意这里使用了 Math.ceil，如果某个权重的值为 0，则始终无法中奖
				let weight = Math.ceil(Math.random() * this.weightTotal)

				let list = [...this.prizeList]

				// 生成大于等于随机权重的数组
				let tempMaxArrs = []
				list.forEach((item) => {
					if (item.weight >= weight) {
						tempMaxArrs.push(item.weight)
					}
				})

				// 如果大于随机权重的数组有值，先对这个数组排序然后取值
				// 反之新建一个临时的包含所有权重的已排序数组，然后取值
				let tempMaxArrsLen = tempMaxArrs.length
				if (tempMaxArrsLen) {
					tempMaxArrs.sort((a, b) => a - b)
					// 取值时，如果存在多个值，分两种情况
					if (tempMaxArrsLen > 1) {
						// 值不相等的情况下取最接近的值，也就是第1个值
						let sumWeight = tempMaxArrs.reduce((a, b) => a + b)
						if ((sumWeight / tempMaxArrsLen) !== tempMaxArrs[0]) {
							this.prizeIndex = this.weightArr.indexOf(tempMaxArrs[0])
						} else {
							// 值相等时，随机取值，当然这里你可以自己决定是否随机取值
							let sameWeight = tempMaxArrs[0]
							let sameWeightArr = []
							let sameWeightItem = {}
							this.weightArr.forEach((item, index) => {
								if (item === sameWeight) {
									sameWeightArr.push({
										weight: item,
										index
									})
								}
							})
							sameWeightItem = sameWeightArr[Math.floor(Math.random() * sameWeightArr.length)]
							this.prizeIndex = sameWeightItem.index
						}
					} else {
						this.prizeIndex = this.weightArr.indexOf(tempMaxArrs[0])
					}
				} else {
					let tempWeightArr = [...this.weightArr]
					tempWeightArr.sort((a, b) => a - b)
					this.prizeIndex = this.weightArr.indexOf(tempWeightArr[tempWeightArr.length - 1])
				}
				// 如果奖品设有库存
				if (this.onStock) {}
			},
			// 远程请求接口获取中奖下标
			remoteGetPrizeIndex() {
				// 模拟请求接口获取中奖信息
				let stoTimer = setTimeout(() => {
					clearTimeout(stoTimer)
					stoTimer = null

					let list = [...this.prizeList]
					// 这里随机产生的 prizeId 是模拟后端返回的 prizeId
					let prizeId = Math.floor(Math.random() * list.length + 1)
					for (let i = 0; i < list.length; i++) {
						let item = list[i]
						if (item.name == this.prizeName) {
							// 中奖下标

							this.prizeIndex = i
							break
						}
					}
					// 如果奖品设有库存
					if (this.onStock) {}
				}, 500)
			},
			// 本次抽奖结束
			handleDrawEnd() {

				// 更新免费次数和金币余额
				if (this.goldCoin >= this.goldNum) this.goldCoin -= this.goldNum

				// 旋转结束后，开始处理拿到结果后的逻辑
				this.prizeing = false
				let prizeName = this.prizeName
				let tipContent = ''

				if (prizeName === '谢谢参与') {
					this.show_regret = true
					// tipContent = '很遗憾，没有中奖，请再接再厉！'
				} else {
					this.targetName = prizeName
					this.show_congratulations = true
				}
			},
			// 抽奖转盘绘制完成
			handleDrawFinish(res) {
				uni.showToast({
					title: res.msg,
					duration: 2000,
					mask: true,
					icon: 'none'
				})
			}
		}
	}
</script>
<style>
	page {
		font: 14px/1.5 "Helvetica Neue", Helvetica, Arial, "Microsoft Yahei", "Hiragino Sans GB", "Heiti SC", "WenQuanYi Micro Hei", sans-serif;
		background: url(https://mystore-1304299581.cos.ap-guangzhou.myqcloud.com/static/image/turntable_bg.png) no-repeat;
		background-size: 100% 100%;
	}
</style>
<style lang="scss" scoped>
	@import './index.scss';
</style>
